home *** CD-ROM | disk | FTP | other *** search
/ Aminet 3 / Aminet 3 - July 1994.iso / Aminet / mus / misc / mpegaudio.lha / mpegaudio / encode.c < prev    next >
C/C++ Source or Header  |  1994-03-21  |  53KB  |  1,417 lines

  1. /**********************************************************************
  2. Copyright (c) 1991 MPEG/audio software simulation group, All Rights Reserved
  3. encode.c
  4. **********************************************************************/
  5. /**********************************************************************
  6.  * MPEG/audio coding/decoding software, work in progress              *
  7.  *   NOT for public distribution until verified and approved by the   *
  8.  *   MPEG/audio committee.  For further information, please contact   *
  9.  *   Davis Pan, 508-493-2241, e-mail: pan@3d.enet.dec.com             *
  10.  *                                                                    *
  11.  * VERSION 3.9t                                                       *
  12.  *   changes made since last update:                                  *
  13.  *   date   programmers         comment                               *
  14.  * 3/01/91  Douglas Wong,       start of version 1.1 records          *
  15.  *          Davis Pan                                                 *
  16.  * 3/06/91  Douglas Wong        rename: setup.h to endef.h            *
  17.  *                                      efilter to enfilter           *
  18.  *                                      ewindow to enwindow           *
  19.  *                              integrated "quantizer", "scalefactor",*
  20.  *                              and "transmission" files              *
  21.  *                              update routine "window_subband"       *
  22.  * 3/31/91  Bill Aspromonte     replaced read_filter by               *
  23.  *                              create_an_filter                      *
  24.  * 5/10/91  W. Joseph Carter    Ported to Macintosh and Unix.         *
  25.  *                              Incorporated Jean-Georges Fritsch's   *
  26.  *                              "bitstream.c" package.                *
  27.  *                              Incorporated Bill Aspromonte's        *
  28.  *                              filterbank coefficient matrix         *
  29.  *                              calculation routines and added        *
  30.  *                              roundoff to coincide with specs.      *
  31.  *                              Modified to strictly adhere to        *
  32.  *                              encoded bitstream specs, including    *
  33.  *                              "Berlin changes".                     *
  34.  *                              Modified PCM sound file handling to   *
  35.  *                              process all incoming samples and fill *
  36.  *                              out last encoded frame with zeros     *
  37.  *                              (silence) if needed.                  *
  38.  *                              Located and fixed numerous software   *
  39.  *                              bugs and table data errors.           *
  40.  * 19jun91  dpwe (Aware)        moved "alloc_*" reader to common.c    *
  41.  *                              Globals sblimit, alloc replaced by new*
  42.  *                              struct 'frame_params' passed as arg.  *
  43.  *                              Added JOINT STEREO coding, layers I,II*
  44.  *                              Affects: *_bit_allocation,            *
  45.  *                              subband_quantization, encode_bit_alloc*
  46.  *                              sample_encoding                       *
  47.  * 6/10/91  Earle Jennings      modified II_subband_quantization to   *
  48.  *                              resolve type cast problem for MS_DOS  *
  49.  * 6/11/91  Earle Jennings      modified to avoid overflow on MS_DOS  *
  50.  *                              in routine filter_subband             *
  51.  * 7/10/91  Earle Jennings      port to MsDos from MacIntosh version  *
  52.  * 8/ 8/91  Jens Spille         Change for MS-C6.00                   *
  53.  *10/ 1/91  S.I. Sudharsanan,   Ported to IBM AIX platform.           *
  54.  *          Don H. Lee,                                               *
  55.  *          Peter W. Farrett                                          *
  56.  *10/ 3/91  Don H. Lee          implemented CRC-16 error protection   *
  57.  *                              newly introduced function encode_CRC  *
  58.  *11/ 8/91  Kathy Wang          Documentation of code                 *
  59.  *                              All variablenames are referred to     *
  60.  *                              with surrounding pound (#) signs      *
  61.  * 2/11/92  W. Joseph Carter    Ported new code to Macintosh.  Most   *
  62.  *                              important fixes involved changing     *
  63.  *                              16-bit ints to long or unsigned in    *
  64.  *                              bit alloc routines for quant of 65535 *
  65.  *                              and passing proper function args.     *
  66.  *                              Removed "Other Joint Stereo" option   *
  67.  *                              and made bitrate be total channel     *
  68.  *                              bitrate, irrespective of the mode.    *
  69.  *                              Fixed many small bugs & reorganized.  *
  70.  * 6/16/92  Shaun Astarabadi    Changed I_scale_factor_calc() and     *
  71.  *                              II_scale_factor_calc() to use scale   *
  72.  *                              factor 0 thru 62 only and not to      *
  73.  *                              encode index 63 into the bit stream.  *
  74.  * 7/27/92  Mike Li             (re-)Port to MS-DOS                   *
  75.  * 9/22/92  jddevine@aware.com  Fixed _scale_factor_calc() defs       *
  76.  * 3/31/93  Giogio Dimino       changed II_a_bit_allocation() from:   *
  77.  *                              if( ad > ...) to if(ad >= ...)        *
  78.  * 8/05/93  TEST                changed I_a_bit_allocation() from:    *
  79.  *                              if( ad > ...) to if(ad >= ...)        *
  80.  **********************************************************************/
  81.  
  82. #include "common.h"
  83. #include "encoder.h"
  84.  
  85. #ifdef MS_DOS
  86. extern unsigned _stklen = 16384;
  87. #endif
  88.  
  89.  
  90. /*=======================================================================\
  91. |                                                                       |
  92. | This segment contains all the core routines of the encoder,           |
  93. | except for the psychoacoustic models.                                 |
  94. |                                                                       |
  95. | The user can select either one of the two psychoacoustic              |
  96. | models. Model I is a simple tonal and noise masking threshold         |
  97. | generator, and Model II is a more sophisticated cochlear masking      |
  98. | threshold generator. Model I is recommended for lower complexity      |
  99. | applications whereas Model II gives better subjective quality at low  |
  100. | bit rates.                                                            |
  101. |                                                                       |
  102. | Layers I and II of mono, stereo, and joint stereo modes are supported.|
  103. | Routines associated with a given layer are prefixed by "I_" for layer |
  104. | 1 and "II_" for layer 2.                                              |
  105. \=======================================================================*/
  106.  
  107. /************************************************************************/
  108. /*
  109. /* read_samples()
  110. /*
  111. /* PURPOSE:  reads the PCM samples from a file to the buffer
  112. /*
  113. /*  SEMANTICS:
  114. /* Reads #samples_read# number of shorts from #musicin# filepointer
  115. /* into #sample_buffer[]#.  Returns the number of samples read.
  116. /*
  117. /************************************************************************/
  118.  
  119. unsigned long read_samples(musicin, sample_buffer, num_samples, frame_size)
  120. FILE *musicin;
  121. short sample_buffer[2304];
  122. unsigned long num_samples, frame_size;
  123. {
  124.     unsigned long samples_read;
  125.     static unsigned long samples_to_read;
  126.     static char init = TRUE;
  127.  
  128.     if (init) {
  129.         samples_to_read = num_samples;
  130.         init = FALSE;
  131.     }
  132.     if (samples_to_read >= frame_size)
  133.         samples_read = frame_size;
  134.     else
  135.         samples_read = samples_to_read;
  136.     if ((samples_read =
  137.          fread(sample_buffer, sizeof(short), (int)samples_read, musicin)) == 0)
  138.         printf("Hit end of audio data\n");
  139.     samples_to_read -= samples_read;
  140.     if (samples_read < frame_size && samples_read > 0) {
  141.         printf("Insufficient PCM input for one frame - fillout with zeros\n");
  142.         for (; samples_read < frame_size; sample_buffer[samples_read++] = 0);
  143.         samples_to_read = 0;
  144.     }
  145.     return(samples_read);
  146. }
  147.  
  148. /************************************************************************/
  149. /*
  150. /* get_audio()
  151. /*
  152. /* PURPOSE:  reads a frame of audio data from a file to the buffer,
  153. /*   aligns the data for future processing, and separates the
  154. /*   left and right channels
  155. /*
  156. /*  SEMANTICS:
  157. /* Calls read_samples() to read a frame of audio data from filepointer
  158. /* #musicin# to #insampl[]#.  The data is shifted to make sure the data
  159. /* is centered for the 1024pt window to be used by the psychoacoustic model,
  160. /* and to compensate for the 256 sample delay from the filter bank. For
  161. /* stereo, the channels are also demultiplexed into #buffer[0][]# and
  162. /* #buffer[1][]#
  163. /*
  164. /************************************************************************/
  165.  
  166. unsigned long get_audio(musicin, buffer, num_samples, stereo, lay)
  167. FILE *musicin;
  168. short FAR buffer[2][1152];
  169. unsigned long num_samples;
  170. int stereo, lay;
  171. {
  172.    int j;
  173.    short insamp[2304];
  174.    unsigned long samples_read;
  175.  
  176.    if (lay == 1){
  177.       if(stereo == 2){ /* layer 1, stereo */
  178.          samples_read = read_samples(musicin, insamp, num_samples,
  179.                                      (unsigned long) 768);
  180.          for(j=0;j<448;j++) {
  181.             if(j<64) {
  182.                buffer[0][j] = buffer[0][j+384];
  183.                buffer[1][j] = buffer[1][j+384];
  184.             }
  185.             else {
  186.                buffer[0][j] = insamp[2*j-128];
  187.                buffer[1][j] = insamp[2*j-127];
  188.             }
  189.          }
  190.       }
  191.       else { /* layer 1, mono */
  192.          samples_read = read_samples(musicin, insamp, num_samples,
  193.                                      (unsigned long) 384);
  194.          for(j=0;j<448;j++){
  195.             if(j<64) {
  196.                buffer[0][j] = buffer[0][j+384];
  197.                buffer[1][j] = 0;
  198.             }
  199.             else {
  200.                buffer[0][j] = insamp[j-64];
  201.                buffer[1][j] = 0;
  202.             }
  203.          }
  204.       }
  205.    }
  206.    else {
  207.       if(stereo == 2){ /* layer 2 (or 3), stereo */
  208.          samples_read = read_samples(musicin, insamp, num_samples,
  209.                                      (unsigned long) 2304);
  210.          for(j=0;j<1152;j++) {
  211.             buffer[0][j] = insamp[2*j];
  212.             buffer[1][j] = insamp[2*j+1];
  213.          }
  214.       }
  215.       else { /* layer 2 (or 3), mono */
  216.          samples_read = read_samples(musicin, insamp, num_samples,
  217.                                      (unsigned long) 1152);
  218.          for(j=0;j<1152;j++){
  219.             buffer[0][j] = insamp[j];
  220.             buffer[1][j] = 0;
  221.          }
  222.       }
  223.    }
  224.    return(samples_read);
  225. }
  226.  
  227. /************************************************************************/
  228. /*
  229. /* read_ana_window()
  230. /*
  231. /* PURPOSE:  Reads encoder window file "enwindow" into array #ana_win#
  232. /*
  233. /************************************************************************/
  234.  
  235. void read_ana_window(ana_win)
  236. double FAR ana_win[HAN_SIZE];
  237. {
  238.     int i,j[4];
  239.     FILE *fp;
  240.     double f[4];
  241.     char t[150];
  242.  
  243.     if (!(fp = OpenTableFile("enwindow") ) ) {
  244.        printf("Please check analysis window table 'enwindow'\n");
  245.        exit(1);
  246.     }
  247.     for (i=0;i<512;i+=4) {
  248.        fgets(t, 150, fp);
  249.        sscanf(t,"C[%d] = %lf C[%d] = %lf C[%d] = %lf C[%d] = %lf\n",
  250.               j, f,j+1,f+1,j+2,f+2,j+3,f+3);
  251.        if (i==j[0]) {
  252.           ana_win[i] = f[0];
  253.           ana_win[i+1] = f[1];
  254.           ana_win[i+2] = f[2];
  255.           ana_win[i+3] = f[3];
  256.        }
  257.        else {
  258.           printf("Check index in analysis window table\n");
  259.           exit(1);
  260.        }
  261.        fgets(t,150,fp);
  262.     }
  263.     fclose(fp);
  264. }
  265.  
  266. /************************************************************************/
  267. /*
  268. /* window_subband()
  269. /*
  270. /* PURPOSE:  Overlapping window on PCM samples
  271. /*
  272. /* SEMANTICS:
  273. /* 32 16-bit pcm samples are scaled to fractional 2's complement and
  274. /* concatenated to the end of the window buffer #x#. The updated window
  275. /* buffer #x# is then windowed by the analysis window #c# to produce the
  276. /* windowed sample #z#
  277. /*
  278. /************************************************************************/
  279.  
  280. void window_subband(buffer, z, k)
  281. short FAR **buffer;
  282. double FAR z[HAN_SIZE];
  283. int k;
  284. {
  285.     typedef double FAR XX[2][HAN_SIZE];
  286.     static XX FAR *x;
  287.     int i, j;
  288.     static off[2] = {0,0};
  289.     static char init = 0;
  290.     static double FAR *c;
  291.     if (!init) {
  292.         c = (double FAR *) mem_alloc(sizeof(double) * HAN_SIZE, "window");
  293.         read_ana_window(c);
  294.         x = (XX FAR *) mem_alloc(sizeof(XX),"x");
  295.         for (i=0;i<2;i++)
  296.             for (j=0;j<HAN_SIZE;j++)
  297.                 (*x)[i][j] = 0;
  298.         init = 1;
  299.     }
  300.  
  301.     /* replace 32 oldest samples with 32 new samples */
  302.     for (i=0;i<32;i++) (*x)[k][31-i+off[k]] = (double) *(*buffer)++/SCALE;
  303.     /* shift samples into proper window positions */
  304.     for (i=0;i<HAN_SIZE;i++) z[i] = (*x)[k][(i+off[k])&HAN_SIZE-1] * c[i];
  305.     off[k] += 480;              /*offset is modulo (HAN_SIZE-1)*/
  306.     off[k] &= HAN_SIZE-1;
  307.  
  308. }
  309.  
  310. /************************************************************************/
  311. /*
  312. /* create_ana_filter()
  313. /*
  314. /* PURPOSE:  Calculates the analysis filter bank coefficients
  315. /*
  316. /* SEMANTICS:
  317. /* Calculates the analysis filterbank coefficients and rounds to the
  318. /* 9th decimal place accuracy of the filterbank tables in the ISO
  319. /* document.  The coefficients are stored in #filter#
  320. /*
  321. /************************************************************************/
  322.  
  323. void create_ana_filter(filter)
  324. double FAR filter[SBLIMIT][64];
  325. {
  326.    register int i,k;
  327.  
  328.    for (i=0; i<32; i++)
  329.       for (k=0; k<64; k++) {
  330.           if ((filter[i][k] = 1e9*cos((double)((2*i+1)*(16-k)*PI64))) >= 0)
  331.              modf(filter[i][k]+0.5, &filter[i][k]);
  332.           else
  333.              modf(filter[i][k]-0.5, &filter[i][k]);
  334.           filter[i][k] *= 1e-9;
  335.    }
  336. }
  337.  
  338. /************************************************************************/
  339. /*
  340. /* filter_subband()
  341. /*
  342. /* PURPOSE:  Calculates the analysis filter bank coefficients
  343. /*
  344. /* SEMANTICS:
  345. /*      The windowed samples #z# is filtered by the digital filter matrix #m#
  346. /* to produce the subband samples #s#. This done by first selectively
  347. /* picking out values from the windowed samples, and then multiplying
  348. /* them by the filter matrix, producing 32 subband samples.
  349. /*
  350. /************************************************************************/
  351.  
  352. void filter_subband(z,s)
  353. double FAR z[HAN_SIZE], s[SBLIMIT];
  354. {
  355.    double y[64];
  356.    int i,j;
  357. static char init = 0;
  358.    typedef double MM[SBLIMIT][64];
  359. static MM FAR *m;
  360. #ifdef MS_DOS
  361.    long    SIZE_OF_MM;
  362.    SIZE_OF_MM      = SBLIMIT*64;
  363.    SIZE_OF_MM      *= 8;
  364.    if (!init) {
  365.        m = (MM FAR *) mem_alloc(SIZE_OF_MM, "filter");
  366.        create_ana_filter(*m);
  367.        init = 1;
  368.    }
  369. #else
  370.    if (!init) {
  371.        m = (MM FAR *) mem_alloc(sizeof(MM), "filter");
  372.        create_ana_filter(*m);
  373.        init = 1;
  374.    }
  375. #endif
  376.    for (i=0;i<64;i++) for (j=0, y[i] = 0;j<8;j++) y[i] += z[i+64*j];
  377.    for (i=0;i<SBLIMIT;i++)
  378.        for (j=0, s[i]= 0;j<64;j++) s[i] += (*m)[i][j] * y[j];
  379. }
  380.  
  381. /************************************************************************/
  382. /*
  383. /* encode_info()
  384. /*
  385. /* PURPOSE:  Puts the syncword and header information on the output
  386. /* bitstream.
  387. /*
  388. /************************************************************************/
  389.  
  390. void encode_info(fr_ps,bs)
  391. frame_params *fr_ps;
  392. Bit_stream_struc *bs;
  393. {
  394.         layer *info = fr_ps->header;
  395.  
  396.         putbits(bs,0xfff,12);                    /* syncword 12 bits */
  397.         put1bit(bs,info->version);               /* ID        1 bit  */
  398.         putbits(bs,4-info->lay,2);               /* layer     2 bits */
  399.         put1bit(bs,!info->error_protection);     /* bit set => no err prot */
  400.         putbits(bs,info->bitrate_index,4);
  401.         putbits(bs,info->sampling_frequency,2);
  402.         put1bit(bs,info->padding);
  403.         put1bit(bs,info->extension);             /* private_bit */
  404.         putbits(bs,info->mode,2);
  405.         putbits(bs,info->mode_ext,2);
  406.         put1bit(bs,info->copyright);
  407.         put1bit(bs,info->original);
  408.         putbits(bs,info->emphasis,2);
  409. }
  410.  
  411. /************************************************************************/
  412. /*
  413. /* mod()
  414. /*
  415. /* PURPOSE:  Returns the absolute value of its argument
  416. /*
  417. /************************************************************************/
  418.  
  419. double mod(a)
  420. double a;
  421. {
  422.     return (a > 0) ? a : -a;
  423. }
  424.  
  425. /************************************************************************/
  426. /*
  427. /* I_combine_LR    (Layer I)
  428. /* II_combine_LR   (Layer II)
  429. /*
  430. /* PURPOSE:Combines left and right channels into a mono channel
  431. /*
  432. /* SEMANTICS:  The average of left and right subband samples is put into
  433. /* #joint_sample#
  434. /*
  435. /* Layer I and II differ in frame length and # subbands used
  436. /*
  437. /************************************************************************/
  438.  
  439. void I_combine_LR(sb_sample, joint_sample)
  440. double FAR sb_sample[2][3][SCALE_BLOCK][SBLIMIT];
  441. double FAR joint_sample[3][SCALE_BLOCK][SBLIMIT];
  442. {   /* make a filtered mono for joint stereo */
  443.     int sb, smp;
  444.  
  445.    for(sb = 0; sb<SBLIMIT; ++sb)
  446.       for(smp = 0; smp<SCALE_BLOCK; ++smp)
  447.         joint_sample[0][smp][sb] = .5 *
  448.                     (sb_sample[0][0][smp][sb] + sb_sample[1][0][smp][sb]);
  449. }
  450.  
  451. void II_combine_LR(sb_sample, joint_sample, sblimit)
  452. double FAR sb_sample[2][3][SCALE_BLOCK][SBLIMIT];
  453. double FAR joint_sample[3][SCALE_BLOCK][SBLIMIT];
  454. int sblimit;
  455. {  /* make a filtered mono for joint stereo */
  456.    int sb, smp, sufr;
  457.  
  458.    for(sb = 0; sb<sblimit; ++sb)
  459.       for(smp = 0; smp<SCALE_BLOCK; ++smp)
  460.          for(sufr = 0; sufr<3; ++sufr)
  461.             joint_sample[sufr][smp][sb] = .5 * (sb_sample[0][sufr][smp][sb]
  462.                                            + sb_sample[1][sufr][smp][sb]);
  463. }
  464.  
  465. /************************************************************************
  466. /*
  467. /* I_scale_factor_calc     (Layer I)
  468. /* II_scale_factor_calc    (Layer II)
  469. /*
  470. /* PURPOSE:For each subband, calculate the scale factor for each set
  471. /* of the 12 subband samples
  472. /*
  473. /* SEMANTICS:  Pick the scalefactor #multiple[]# just larger than the
  474. /* absolute value of the peak subband sample of 12 samples,
  475. /* and store the corresponding scalefactor index in #scalar#.
  476. /*
  477. /* Layer II has three sets of 12-subband samples for a given
  478. /* subband.
  479. /*
  480. /************************************************************************/
  481.  
  482. void I_scale_factor_calc(sb_sample,scalar,stereo)
  483. double FAR sb_sample[][3][SCALE_BLOCK][SBLIMIT];
  484. unsigned int scalar[][3][SBLIMIT];
  485. int stereo;
  486. {
  487.    int i,j, k;
  488.    double s[SBLIMIT];
  489.  
  490.    for (k=0;k<stereo;k++) {
  491.      for (i=0;i<SBLIMIT;i++)
  492.        for (j=1, s[i] = mod(sb_sample[k][0][0][i]);j<SCALE_BLOCK;j++)
  493.          if (mod(sb_sample[k][0][j][i]) > s[i])
  494.             s[i] = mod(sb_sample[k][0][j][i]);
  495.  
  496.      for (i=0;i<SBLIMIT;i++)
  497.        for (j=SCALE_RANGE-2,scalar[k][0][i]=0;j>=0;j--) /* $A 6/16/92 */
  498.          if (s[i] <= multiple[j]) {
  499.             scalar[k][0][i] = j;
  500.             break;
  501.          }
  502.    }
  503. }
  504.  
  505. /******************************** Layer II ******************************/
  506.  
  507. void II_scale_factor_calc(sb_sample,scalar,stereo,sblimit)
  508. double FAR sb_sample[][3][SCALE_BLOCK][SBLIMIT];
  509. unsigned int scalar[][3][SBLIMIT];
  510. int stereo,sblimit;
  511. {
  512.   int i,j, k,t;
  513.   double s[SBLIMIT];
  514.  
  515.   for (k=0;k<stereo;k++) for (t=0;t<3;t++) {
  516.     for (i=0;i<sblimit;i++)
  517.       for (j=1, s[i] = mod(sb_sample[k][t][0][i]);j<SCALE_BLOCK;j++)
  518.         if (mod(sb_sample[k][t][j][i]) > s[i])
  519.              s[i] = mod(sb_sample[k][t][j][i]);
  520.  
  521.   for (i=0;i<sblimit;i++)
  522.     for (j=SCALE_RANGE-2,scalar[k][t][i]=0;j>=0;j--)    /* $A 6/16/92 */
  523.       if (s[i] <= multiple[j]) {
  524.          scalar[k][t][i] = j;
  525.          break;
  526.       }
  527.       for (i=sblimit;i<SBLIMIT;i++) scalar[k][t][i] = SCALE_RANGE-1;
  528.     }
  529. }
  530.  
  531. /************************************************************************
  532. /*
  533. /* pick_scale  (Layer II)
  534. /*
  535. /* PURPOSE:For each subband, puts the smallest scalefactor of the 3
  536. /* associated with a frame into #max_sc#.  This is used
  537. /* used by Psychoacoustic Model I.
  538. /* (I would recommend changin max_sc to min_sc)
  539. /*
  540. /************************************************************************/
  541.  
  542. void pick_scale(scalar, fr_ps, max_sc)
  543. unsigned int scalar[2][3][SBLIMIT];
  544. frame_params *fr_ps;
  545. double FAR max_sc[2][SBLIMIT];
  546. {
  547.   int i,j,k,max;
  548.   int stereo  = fr_ps->stereo;
  549.   int sblimit = fr_ps->sblimit;
  550.  
  551.   for (k=0;k<stereo;k++)
  552.     for (i=0;i<sblimit;max_sc[k][i] = multiple[max],i++)
  553.       for (j=1, max = scalar[k][0][i];j<3;j++)
  554.          if (max > scalar[k][j][i]) max = scalar[k][j][i];
  555.   for (i=sblimit;i<SBLIMIT;i++) max_sc[0][i] = max_sc[1][i] = 1E-20;
  556. }
  557.  
  558. /************************************************************************
  559. /*
  560. /* put_scale   (Layer I)
  561. /*
  562. /* PURPOSE:Sets #max_sc# to the scalefactor index in #scalar.
  563. /* This is used by Psychoacoustic Model I
  564. /*
  565. /************************************************************************/
  566.  
  567. void put_scale(scalar, fr_ps, max_sc)
  568. unsigned int scalar[2][3][SBLIMIT];
  569. frame_params *fr_ps;
  570. double FAR max_sc[2][SBLIMIT];
  571. {
  572.    int i,j,k, max;
  573.    int stereo  = fr_ps->stereo;
  574.    int sblimit = fr_ps->sblimit;
  575.  
  576.    for (k=0;k<stereo;k++) for (i=0;i<SBLIMIT;i++)
  577.         max_sc[k][i] = multiple[scalar[k][0][i]];
  578. }
  579.  
  580. /************************************************************************
  581. /*
  582. /* II_transmission_pattern (Layer II only)
  583. /*
  584. /* PURPOSE:For a given subband, determines whether to send 1, 2, or
  585. /* all 3 of the scalefactors, and fills in the scalefactor
  586. /* select information accordingly
  587. /*
  588. /* SEMANTICS:  The subbands and channels are classified based on how much
  589. /* the scalefactors changes over its three values (corresponding
  590. /* to the 3 sets of 12 samples per subband).  The classification
  591. /* will send 1 or 2 scalefactors instead of three if the scalefactors
  592. /* do not change much.  The scalefactor select information,
  593. /* #scfsi#, is filled in accordingly.
  594. /*
  595. /************************************************************************/
  596.  
  597. void II_transmission_pattern(scalar, scfsi, fr_ps)
  598. unsigned int scalar[2][3][SBLIMIT];
  599. unsigned int scfsi[2][SBLIMIT];
  600. frame_params *fr_ps;
  601. {
  602.    int stereo  = fr_ps->stereo;
  603.    int sblimit = fr_ps->sblimit;
  604.    int dscf[2];
  605.    int class[2],i,j,k;
  606. static int pattern[5][5] = {0x123, 0x122, 0x122, 0x133, 0x123,
  607.                             0x113, 0x111, 0x111, 0x444, 0x113,
  608.                             0x111, 0x111, 0x111, 0x333, 0x113,
  609.                             0x222, 0x222, 0x222, 0x333, 0x123,
  610.                             0x123, 0x122, 0x122, 0x133, 0x123};
  611.  
  612.    for (k=0;k<stereo;k++)
  613.      for (i=0;i<sblimit;i++) {
  614.        dscf[0] =  (scalar[k][0][i]-scalar[k][1][i]);
  615.        dscf[1] =  (scalar[k][1][i]-scalar[k][2][i]);
  616.        for (j=0;j<2;j++) {
  617.          if (dscf[j]<=-3) class[j] = 0;
  618.          else if (dscf[j] > -3 && dscf[j] <0) class[j] = 1;
  619.               else if (dscf[j] == 0) class[j] = 2;
  620.                    else if (dscf[j] > 0 && dscf[j] < 3) class[j] = 3;
  621.                         else class[j] = 4;
  622.        }
  623.        switch (pattern[class[0]][class[1]]) {
  624.          case 0x123 :    scfsi[k][i] = 0;
  625.                          break;
  626.          case 0x122 :    scfsi[k][i] = 3;
  627.                          scalar[k][2][i] = scalar[k][1][i];
  628.                          break;
  629.          case 0x133 :    scfsi[k][i] = 3;
  630.                          scalar[k][1][i] = scalar[k][2][i];
  631.                          break;
  632.          case 0x113 :    scfsi[k][i] = 1;
  633.                          scalar[k][1][i] = scalar[k][0][i];
  634.                          break;
  635.          case 0x111 :    scfsi[k][i] = 2;
  636.                          scalar[k][1][i] = scalar[k][2][i] = scalar[k][0][i];
  637.                          break;
  638.          case 0x222 :    scfsi[k][i] = 2;
  639.                          scalar[k][0][i] = scalar[k][2][i] = scalar[k][1][i];
  640.                          break;
  641.          case 0x333 :    scfsi[k][i] = 2;
  642.                          scalar[k][0][i] = scalar[k][1][i] = scalar[k][2][i];
  643.                          break;
  644.          case 0x444 :    scfsi[k][i] = 2;
  645.                          if (scalar[k][0][i] > scalar[k][2][i])
  646.                               scalar[k][0][i] = scalar[k][2][i];
  647.                          scalar[k][1][i] = scalar[k][2][i] = scalar[k][0][i];
  648.       }
  649.    }
  650. }
  651.  
  652. /************************************************************************
  653. /*
  654. /* I_encode_scale  (Layer I)
  655. /* II_encode_scale (Layer II)
  656. /*
  657. /* PURPOSE:The encoded scalar factor information is arranged and
  658. /* queued into the output fifo to be transmitted.
  659. /*
  660. /* For Layer II, the three scale factors associated with
  661. /* a given subband and channel are transmitted in accordance
  662. /* with the scfsi, which is transmitted first.
  663. /*
  664. /************************************************************************/
  665.  
  666. void I_encode_scale(scalar, bit_alloc, fr_ps, bs)
  667. unsigned int scalar[2][3][SBLIMIT];
  668. unsigned int bit_alloc[2][SBLIMIT];
  669. frame_params *fr_ps;
  670. Bit_stream_struc *bs;
  671. {
  672.    int stereo  = fr_ps->stereo;
  673.    int sblimit = fr_ps->sblimit;
  674.    int i,j;
  675.  
  676.    for (i=0;i<SBLIMIT;i++) for (j=0;j<stereo;j++)
  677.       if (bit_alloc[j][i]) putbits(bs,scalar[j][0][i],6);
  678. }
  679.  
  680. /***************************** Layer II  ********************************/
  681.  
  682. void II_encode_scale(bit_alloc, scfsi, scalar, fr_ps, bs)
  683. unsigned int bit_alloc[2][SBLIMIT], scfsi[2][SBLIMIT];
  684. unsigned int scalar[2][3][SBLIMIT];
  685. frame_params *fr_ps;
  686. Bit_stream_struc *bs;
  687. {
  688.    int stereo  = fr_ps->stereo;
  689.    int sblimit = fr_ps->sblimit;
  690.    int jsbound = fr_ps->jsbound;
  691.    int i,j,k;
  692.  
  693.    for (i=0;i<sblimit;i++) for (k=0;k<stereo;k++)
  694.      if (bit_alloc[k][i])  putbits(bs,scfsi[k][i],2);
  695.  
  696.    for (i=0;i<sblimit;i++) for (k=0;k<stereo;k++)
  697.      if (bit_alloc[k][i])  /* above jsbound, bit_alloc[0][i] == ba[1][i] */
  698.         switch (scfsi[k][i]) {
  699.            case 0: for (j=0;j<3;j++)
  700.                      putbits(bs,scalar[k][j][i],6);
  701.                    break;
  702.            case 1:
  703.            case 3: putbits(bs,scalar[k][0][i],6);
  704.                    putbits(bs,scalar[k][2][i],6);
  705.                    break;
  706.            case 2: putbits(bs,scalar[k][0][i],6);
  707.         }
  708. }
  709.  
  710. /*=======================================================================\
  711. |                                                                        |
  712. |      The following routines are done after the masking threshold       |
  713. | has been calculated by the fft analysis routines in the Psychoacoustic |
  714. | model. Using the MNR calculated, the actual number of bits allocated   |
  715. | to each subband is found iteratively.                                  |
  716. |                                                                        |
  717. \=======================================================================*/
  718.  
  719. /************************************************************************
  720. /*
  721. /* I_bits_for_nonoise  (Layer I)
  722. /* II_bits_for_nonoise (Layer II)
  723. /*
  724. /* PURPOSE:Returns the number of bits required to produce a
  725. /* mask-to-noise ratio better or equal to the noise/no_noise threshold.
  726. /*
  727. /* SEMANTICS:
  728. /* bbal = # bits needed for encoding bit allocation
  729. /* bsel = # bits needed for encoding scalefactor select information
  730. /* banc = # bits needed for ancillary data (header info included)
  731. /*
  732. /* For each subband and channel, will add bits until one of the
  733. /* following occurs:
  734. /* - Hit maximum number of bits we can allocate for that subband
  735. /* - MNR is better than or equal to the minimum masking level
  736. /*   (NOISY_MIN_MNR)
  737. /* Then the bits required for scalefactors, scfsi, bit allocation,
  738. /* and the subband samples are tallied (#req_bits#) and returned.
  739. /*
  740. /* (NOISY_MIN_MNR) is the smallest MNR a subband can have before it is
  741. /* counted as 'noisy' by the logic which chooses the number of JS
  742. /* subbands.
  743. /*
  744. /* Joint stereo is supported.
  745. /*
  746. /************************************************************************/
  747.  
  748. static double snr[18] = {0.00, 7.00, 11.00, 16.00, 20.84,
  749.                          25.28, 31.59, 37.75, 43.84,
  750.                          49.89, 55.93, 61.96, 67.98, 74.01,
  751.                          80.03, 86.05, 92.01, 98.01};
  752.  
  753. int I_bits_for_nonoise(perm_smr, fr_ps)
  754. double FAR perm_smr[2][SBLIMIT];
  755. frame_params *fr_ps;
  756. {
  757.    int i,j,k;
  758.    int stereo  = fr_ps->stereo;
  759.    int sblimit = fr_ps->sblimit;
  760.    int jsbound = fr_ps->jsbound;
  761.    int req_bits = 0;
  762.  
  763.    /* initial b_anc (header) allocation bits */
  764.    req_bits = 32 + 4 * ( (jsbound * stereo) + (SBLIMIT-jsbound) );
  765.  
  766.    for(i=0; i<SBLIMIT; ++i)
  767.      for(j=0; j<((i<jsbound)?stereo:1); ++j) {
  768.        for(k=0;k<14; ++k)
  769.          if( (-perm_smr[j][i] + snr[k]) >= NOISY_MIN_MNR)
  770.            break; /* we found enough bits */
  771.          if(stereo == 2 && i >= jsbound)     /* check other JS channel */
  772.            for(;k<14; ++k)
  773.              if( (-perm_smr[1-j][i] + snr[k]) >= NOISY_MIN_MNR) break;
  774.          if(k>0) req_bits += (k+1)*SCALE_BLOCK + 6*((i>=jsbound)?stereo:1);
  775.    }
  776.    return req_bits;
  777. }
  778.  
  779. /***************************** Layer II  ********************************/
  780.  
  781. int II_bits_for_nonoise(perm_smr, scfsi, fr_ps)
  782. double FAR perm_smr[2][SBLIMIT];
  783. unsigned int scfsi[2][SBLIMIT];
  784. frame_params *fr_ps;
  785. {
  786.    int sb,ch,ba;
  787.    int stereo  = fr_ps->stereo;
  788.    int sblimit = fr_ps->sblimit;
  789.    int jsbound = fr_ps->jsbound;
  790.    al_table *alloc = fr_ps->alloc;
  791.    int req_bits = 0, bbal = 0, berr = 0, banc = 32;
  792.    int maxAlloc, sel_bits, sc_bits, smp_bits;
  793. static int sfsPerScfsi[] = { 3,2,1,2 };    /* lookup # sfs per scfsi */
  794.  
  795.    /* added 92-08-11 shn */
  796.    if (fr_ps->header->error_protection) berr=16; else berr=0; 
  797.  
  798.    for (sb=0; sb<jsbound; ++sb)
  799.      bbal += stereo * (*alloc)[sb][0].bits;
  800.    for (sb=jsbound; sb<sblimit; ++sb)
  801.      bbal += (*alloc)[sb][0].bits;
  802.    req_bits = banc + bbal + berr;
  803.  
  804.    for(sb=0; sb<sblimit; ++sb)
  805.      for(ch=0; ch<((sb<jsbound)?stereo:1); ++ch) {
  806.        maxAlloc = (1<<(*alloc)[sb][0].bits)-1;
  807.        sel_bits = sc_bits = smp_bits = 0;
  808.        for(ba=0;ba<maxAlloc-1; ++ba)
  809.          if( (-perm_smr[ch][sb] + snr[(*alloc)[sb][ba].quant+((ba>0)?1:0)])
  810.              >= NOISY_MIN_MNR)
  811.             break;      /* we found enough bits */
  812.        if(stereo == 2 && sb >= jsbound) /* check other JS channel */
  813.          for(;ba<maxAlloc-1; ++ba)
  814.            if( (-perm_smr[1-ch][sb]+ snr[(*alloc)[sb][ba].quant+((ba>0)?1:0)])
  815.                >= NOISY_MIN_MNR)
  816.              break;
  817.        if(ba>0) {
  818.          smp_bits = SCALE_BLOCK * ((*alloc)[sb][ba].group * (*alloc)[sb][ba].bits);
  819.          /* scale factor bits required for subband */
  820.          sel_bits = 2;
  821.          sc_bits  = 6 * sfsPerScfsi[scfsi[ch][sb]];
  822.          if(stereo == 2 && sb >= jsbound) {
  823.            /* each new js sb has L+R scfsis */
  824.            sel_bits += 2;
  825.            sc_bits  += 6 * sfsPerScfsi[scfsi[1-ch][sb]];
  826.          }
  827.          req_bits += smp_bits+sel_bits+sc_bits;
  828.        }
  829.    }
  830.    return req_bits;
  831. }
  832.  
  833. /************************************************************************
  834. /*
  835. /* I_main_bit_allocation   (Layer I)
  836. /* II_main_bit_allocation  (Layer II)
  837. /*
  838. /* PURPOSE:For joint stereo mode, determines which of the 4 joint
  839. /* stereo modes is needed.  Then calls *_a_bit_allocation(), which
  840. /* allocates bits for each of the subbands until there are no more bits
  841. /* left, or the MNR is at the noise/no_noise threshold.
  842. /*
  843. /* SEMANTICS:
  844. /*
  845. /* For joint stereo mode, joint stereo is changed to stereo if
  846. /* there are enough bits to encode stereo at or better than the
  847. /* no-noise threshold (NOISY_MIN_MNR).  Otherwise, the system
  848. /* iteratively allocates less bits by using joint stereo until one
  849. /* of the following occurs:
  850. /* - there are no more noisy subbands (MNR >= NOISY_MIN_MNR)
  851. /* - mode_ext has been reduced to 0, which means that all but the
  852. /*   lowest 4 subbands have been converted from stereo to joint
  853. /*   stereo, and no more subbands may be converted
  854. /*
  855. /*     This function calls *_bits_for_nonoise() and *_a_bit_allocation().
  856. /*
  857. /************************************************************************/
  858.  
  859. void I_main_bit_allocation(perm_smr, bit_alloc, adb, fr_ps)
  860. double FAR perm_smr[2][SBLIMIT];
  861. unsigned int bit_alloc[2][SBLIMIT];
  862. int *adb;
  863. frame_params *fr_ps;
  864. {
  865.    int  noisy_sbs;
  866.    int  mode, mode_ext, lay, i;
  867.    int  rq_db, av_db = *adb;
  868. static  int init = 0;
  869.  
  870.    if(init == 0) {
  871.      /* rearrange snr for layer I */
  872.      snr[2] = snr[3];
  873.      for (i=3;i<16;i++) snr[i] = snr[i+2];
  874.      init = 1;
  875.    }
  876.  
  877.    if((mode = fr_ps->actual_mode) == MPG_MD_JOINT_STEREO) {
  878.      fr_ps->header->mode = MPG_MD_STEREO;
  879.      fr_ps->header->mode_ext = 0;
  880.      fr_ps->jsbound = fr_ps->sblimit;
  881.      if(rq_db = I_bits_for_nonoise(perm_smr, fr_ps) > *adb) {
  882.        fr_ps->header->mode = MPG_MD_JOINT_STEREO;
  883.        mode_ext = 4;           /* 3 is least severe reduction */
  884.        lay = fr_ps->header->lay;
  885.        do {
  886.           --mode_ext;
  887.           fr_ps->jsbound = js_bound(lay, mode_ext);
  888.           rq_db = I_bits_for_nonoise(perm_smr, fr_ps);
  889.        } while( (rq_db > *adb) && (mode_ext > 0));
  890.        fr_ps->header->mode_ext = mode_ext;
  891.      }    /* well we either eliminated noisy sbs or mode_ext == 0 */
  892.    }
  893.    noisy_sbs = I_a_bit_allocation(perm_smr, bit_alloc, adb, fr_ps);
  894. }
  895.  
  896. /***************************** Layer II  ********************************/
  897.  
  898. void II_main_bit_allocation(perm_smr, scfsi, bit_alloc, adb, fr_ps)
  899. double FAR perm_smr[2][SBLIMIT];
  900. unsigned int scfsi[2][SBLIMIT];
  901. unsigned int bit_alloc[2][SBLIMIT];
  902. int *adb;
  903. frame_params *fr_ps;
  904. {
  905.    int  noisy_sbs, nn;
  906.    int  mode, mode_ext, lay;
  907.    int  rq_db, av_db = *adb;
  908.  
  909.    if((mode = fr_ps->actual_mode) == MPG_MD_JOINT_STEREO) {
  910.      fr_ps->header->mode = MPG_MD_STEREO;
  911.      fr_ps->header->mode_ext = 0;
  912.      fr_ps->jsbound = fr_ps->sblimit;
  913.      if((rq_db=II_bits_for_nonoise(perm_smr, scfsi, fr_ps)) > *adb) {
  914.        fr_ps->header->mode = MPG_MD_JOINT_STEREO;
  915.        mode_ext = 4;           /* 3 is least severe reduction */
  916.        lay = fr_ps->header->lay;
  917.        do {
  918.          --mode_ext;
  919.          fr_ps->jsbound = js_bound(lay, mode_ext);
  920.          rq_db = II_bits_for_nonoise(perm_smr, scfsi, fr_ps);
  921.        } while( (rq_db > *adb) && (mode_ext > 0));
  922.        fr_ps->header->mode_ext = mode_ext;
  923.      }    /* well we either eliminated noisy sbs or mode_ext == 0 */
  924.    }
  925.    noisy_sbs = II_a_bit_allocation(perm_smr, scfsi, bit_alloc, adb, fr_ps);
  926. }
  927.  
  928. /************************************************************************
  929. /*
  930. /* I_a_bit_allocation  (Layer I)
  931. /* II_a_bit_allocation (Layer II)
  932. /*
  933. /* PURPOSE:Adds bits to the subbands with the lowest mask-to-noise
  934. /* ratios, until the maximum number of bits for the subband has
  935. /* been allocated.
  936. /*
  937. /* SEMANTICS:
  938. /* 1. Find the subband and channel with the smallest MNR (#min_sb#,
  939. /*    and #min_ch#)
  940. /* 2. Calculate the increase in bits needed if we increase the bit
  941. /*    allocation to the next higher level
  942. /* 3. If there are enough bits available for increasing the resolution
  943. /*    in #min_sb#, #min_ch#, and the subband has not yet reached its
  944. /*    maximum allocation, update the bit allocation, MNR, and bits
  945. /*    available accordingly
  946. /* 4. Repeat until there are no more bits left, or no more available
  947. /*    subbands. (A subband is still available until the maximum
  948. /*    number of bits for the subband has been allocated, or there
  949. /*    aren't enough bits to go to the next higher resolution in the
  950. /*    subband.)
  951. /*
  952. /************************************************************************/
  953.  
  954. int I_a_bit_allocation(perm_smr, bit_alloc, adb, fr_ps) /* return noisy sbs */
  955. double FAR perm_smr[2][SBLIMIT];
  956. unsigned int bit_alloc[2][SBLIMIT];
  957. int *adb;
  958. frame_params *fr_ps;
  959. {
  960.    int i, k, smpl_bits, scale_bits, min_sb, min_ch, oth_ch;
  961.    int bspl, bscf, ad, noisy_sbs, done = 0, bbal ;
  962.    double mnr[2][SBLIMIT], small;
  963.    char used[2][SBLIMIT];
  964.    int stereo  = fr_ps->stereo;
  965.    int sblimit = fr_ps->sblimit;
  966.    int jsbound = fr_ps->jsbound;
  967.    al_table *alloc = fr_ps->alloc;
  968. static char init= 0;
  969. static int banc=32, berr=0;
  970.  
  971.    if (!init) {
  972.       init = 1;
  973.       if (fr_ps->header->error_protection) berr = 16;  /* added 92-08-11 shn */
  974.    }
  975.    bbal = 4 * ( (jsbound * stereo) + (SBLIMIT-jsbound) );
  976.    *adb -= bbal + berr + banc;
  977.    ad= *adb;
  978.  
  979.    for (i=0;i<SBLIMIT;i++) for (k=0;k<stereo;k++) {
  980.      mnr[k][i]=snr[0]-perm_smr[k][i];
  981.      bit_alloc[k][i] = 0;
  982.      used[k][i] = 0;
  983.    }
  984.    bspl = bscf = 0;
  985.  
  986.    do  {
  987.      /* locate the subband with minimum SMR */
  988.      small = mnr[0][0]+1;    min_sb = -1; min_ch = -1;
  989.      for (i=0;i<SBLIMIT;i++) for (k=0;k<stereo;k++)
  990.        /* go on only if there are bits left */
  991.        if (used[k][i] != 2 && small > mnr[k][i]) {
  992.          small = mnr[k][i];
  993.          min_sb = i;  min_ch = k;
  994.        }
  995.      if(min_sb > -1) {   /* there was something to find */
  996.        /* first step of bit allocation is biggest */
  997.        if (used[min_ch][min_sb])  { smpl_bits = SCALE_BLOCK; scale_bits = 0; }
  998.        else                       { smpl_bits = 24; scale_bits = 6; }
  999.        if(min_sb >= jsbound)        scale_bits *= stereo;
  1000.  
  1001.        /* check to see enough bits were available for */
  1002.        /* increasing resolution in the minimum band */
  1003.  
  1004.        if (ad >= bspl + bscf + scale_bits + smpl_bits) {
  1005.          bspl += smpl_bits; /* bit for subband sample */
  1006.          bscf += scale_bits; /* bit for scale factor */
  1007.          bit_alloc[min_ch][min_sb]++;
  1008.          used[min_ch][min_sb] = 1; /* subband has bits */
  1009.          mnr[min_ch][min_sb] = -perm_smr[min_ch][min_sb]
  1010.                                + snr[bit_alloc[min_ch][min_sb]];
  1011.          /* Check if subband has been fully allocated max bits */
  1012.          if (bit_alloc[min_ch][min_sb] ==  14 ) used[min_ch][min_sb] = 2;
  1013.        }
  1014.        else            /* no room to improve this band */
  1015.          used[min_ch][min_sb] = 2; /*   for allocation anymore */
  1016.        if(stereo == 2 && min_sb >= jsbound) {
  1017.          oth_ch = 1-min_ch;  /* joint-st : fix other ch */
  1018.          bit_alloc[oth_ch][min_sb] = bit_alloc[min_ch][min_sb];
  1019.          used[oth_ch][min_sb] = used[min_ch][min_sb];
  1020.          mnr[oth_ch][min_sb] = -perm_smr[oth_ch][min_sb]
  1021.                                + snr[bit_alloc[oth_ch][min_sb]];
  1022.        }
  1023.      }
  1024.    } while(min_sb>-1);     /* i.e. still some sub-bands to find */
  1025.  
  1026.    /* Calculate the number of bits left, add on to pointed var */
  1027.    ad -= bspl+bscf;
  1028.    *adb = ad;
  1029.  
  1030.    /* see how many channels are noisy */
  1031.    noisy_sbs = 0; small = mnr[0][0];
  1032.    for(k=0; k<stereo; ++k) {
  1033.      for(i = 0; i< SBLIMIT; ++i) {
  1034.        if(mnr[k][i] < NOISY_MIN_MNR)   ++noisy_sbs;
  1035.        if(small > mnr[k][i])           small = mnr[k][i];
  1036.      }
  1037.    }
  1038.    return noisy_sbs;
  1039. }
  1040.  
  1041. /***************************** Layer II  ********************************/
  1042.  
  1043. int II_a_bit_allocation(perm_smr, scfsi, bit_alloc, adb, fr_ps)
  1044. double FAR perm_smr[2][SBLIMIT];
  1045. unsigned int scfsi[2][SBLIMIT];
  1046. unsigned int bit_alloc[2][SBLIMIT];
  1047. int *adb;
  1048. frame_params *fr_ps;
  1049. {
  1050.    int i, min_ch, min_sb, oth_ch, k, increment, scale, seli, ba;
  1051.    int bspl, bscf, bsel, ad, noisy_sbs, bbal=0;
  1052.    double mnr[2][SBLIMIT], small;
  1053.    char used[2][SBLIMIT];
  1054.    int stereo  = fr_ps->stereo;
  1055.    int sblimit = fr_ps->sblimit;
  1056.    int jsbound = fr_ps->jsbound;
  1057.    al_table *alloc = fr_ps->alloc;
  1058. static char init= 0;
  1059. static int banc=32, berr=0;
  1060. static int sfsPerScfsi[] = { 3,2,1,2 };    /* lookup # sfs per scfsi */
  1061.  
  1062.    if (!init) { 
  1063.        init = 1;  
  1064.        if (fr_ps->header->error_protection) berr=16; /* added 92-08-11 shn */
  1065.    }
  1066.    for (i=0; i<jsbound; ++i)
  1067.      bbal += stereo * (*alloc)[i][0].bits;
  1068.    for (i=jsbound; i<sblimit; ++i)
  1069.      bbal += (*alloc)[i][0].bits;
  1070.    *adb -= bbal + berr + banc;
  1071.    ad = *adb;
  1072.  
  1073.    for (i=0;i<sblimit;i++) for (k=0;k<stereo;k++) {
  1074.      mnr[k][i]=snr[0]-perm_smr[k][i];
  1075.      bit_alloc[k][i] = 0;
  1076.      used[k][i] = 0;
  1077.    }
  1078.    bspl = bscf = bsel = 0;
  1079.  
  1080.    do  {
  1081.      /* locate the subband with minimum SMR */
  1082.      small = 999999.0; min_sb = -1; min_ch = -1;
  1083.      for (i=0;i<sblimit;i++) for(k=0;k<stereo;++k)
  1084.        if (used[k][i]  != 2 && small > mnr[k][i]) {
  1085.          small = mnr[k][i];
  1086.          min_sb = i;  min_ch = k;
  1087.      }
  1088.      if(min_sb > -1) {   /* there was something to find */
  1089.        /* find increase in bit allocation in subband [min] */
  1090.        increment = SCALE_BLOCK * ((*alloc)[min_sb][bit_alloc[min_ch][min_sb]+1].group *
  1091.                         (*alloc)[min_sb][bit_alloc[min_ch][min_sb]+1].bits);
  1092.        if (used[min_ch][min_sb])
  1093.          increment -= SCALE_BLOCK * ((*alloc)[min_sb][bit_alloc[min_ch][min_sb]].group*
  1094.                            (*alloc)[min_sb][bit_alloc[min_ch][min_sb]].bits);
  1095.  
  1096.        /* scale factor bits required for subband [min] */
  1097.        oth_ch = 1 - min_ch;    /* above js bound, need both chans */
  1098.        if (used[min_ch][min_sb]) scale = seli = 0;
  1099.        else {          /* this channel had no bits or scfs before */
  1100.          seli = 2;
  1101.          scale = 6 * sfsPerScfsi[scfsi[min_ch][min_sb]];
  1102.          if(stereo == 2 && min_sb >= jsbound) {
  1103.            /* each new js sb has L+R scfsis */
  1104.            seli += 2;
  1105.            scale += 6 * sfsPerScfsi[scfsi[oth_ch][min_sb]];
  1106.          }
  1107.        }
  1108.        /* check to see enough bits were available for */
  1109.        /* increasing resolution in the minimum band */
  1110.        if (ad >= bspl + bscf + bsel + seli + scale + increment) {
  1111.          ba = ++bit_alloc[min_ch][min_sb]; /* next up alloc */
  1112.          bspl += increment;  /* bits for subband sample */
  1113.          bscf += scale;      /* bits for scale factor */
  1114.          bsel += seli;       /* bits for scfsi code */
  1115.          used[min_ch][min_sb] = 1; /* subband has bits */
  1116.          mnr[min_ch][min_sb] = -perm_smr[min_ch][min_sb] +
  1117.                                snr[(*alloc)[min_sb][ba].quant+1];
  1118.          /* Check if subband has been fully allocated max bits */
  1119.          if (ba >= (1<<(*alloc)[min_sb][0].bits)-1) used[min_ch][min_sb] = 2;
  1120.        }
  1121.        else used[min_ch][min_sb] = 2; /* can't increase this alloc */
  1122.        if(min_sb >= jsbound && stereo == 2) {
  1123.          /* above jsbound, alloc applies L+R */
  1124.          ba = bit_alloc[oth_ch][min_sb] = bit_alloc[min_ch][min_sb];
  1125.          used[oth_ch][min_sb] = used[min_ch][min_sb];
  1126.          mnr[oth_ch][min_sb] = -perm_smr[oth_ch][min_sb] +
  1127.                                snr[(*alloc)[min_sb][ba].quant+1];
  1128.        }
  1129.      }
  1130.    } while(min_sb > -1);   /* until could find no channel */
  1131.    /* Calculate the number of bits left */
  1132.    ad -= bspl+bscf+bsel;   *adb = ad;
  1133.    for (i=sblimit;i<SBLIMIT;i++) for (k=0;k<stereo;k++) bit_alloc[k][i]=0;
  1134.  
  1135.    noisy_sbs = 0;  small = mnr[0][0];      /* calc worst noise in case */
  1136.    for(k=0;k<stereo;++k) {
  1137.      for (i=0;i<sblimit;i++) {
  1138.        if (small > mnr[k][i]) small = mnr[k][i];
  1139.        if(mnr[k][i] < NOISY_MIN_MNR) ++noisy_sbs; /* noise is not masked */
  1140.  
  1141.      }
  1142.    }
  1143.    return noisy_sbs;
  1144. }
  1145.  
  1146. /************************************************************************
  1147. /*
  1148. /* I_subband_quantization  (Layer I)
  1149. /* II_subband_quantization (Layer II)
  1150. /*
  1151. /* PURPOSE:Quantizes subband samples to appropriate number of bits
  1152. /*
  1153. /* SEMANTICS:  Subband samples are divided by their scalefactors, which
  1154. /* makes the quantization more efficient. The scaled samples are
  1155. /* quantized by the function a*x+b, where a and b are functions of
  1156. /* the number of quantization levels. The result is then truncated
  1157. /* to the appropriate number of bits and the MSB is inverted.
  1158. /*
  1159. /* Note that for fractional 2's complement, inverting the MSB for a
  1160. /* negative number x is equivalent to adding 1 to it.
  1161. /*
  1162. /************************************************************************/
  1163.  
  1164. static double a[17] = {
  1165.   0.750000000, 0.625000000, 0.875000000, 0.562500000, 0.937500000,
  1166.   0.968750000, 0.984375000, 0.992187500, 0.996093750, 0.998046875,
  1167.   0.999023438, 0.999511719, 0.999755859, 0.999877930, 0.999938965,
  1168.   0.999969482, 0.999984741 };
  1169.  
  1170. static double b[17] = {
  1171.   -0.250000000, -0.375000000, -0.125000000, -0.437500000, -0.062500000,
  1172.   -0.031250000, -0.015625000, -0.007812500, -0.003906250, -0.001953125,
  1173.   -0.000976563, -0.000488281, -0.000244141, -0.000122070, -0.000061035,
  1174.   -0.000030518, -0.000015259 };
  1175.  
  1176. void I_subband_quantization(scalar, sb_samples, j_scale, j_samps,
  1177.                             bit_alloc, sbband, fr_ps)
  1178. unsigned int scalar[2][3][SBLIMIT];
  1179. double FAR sb_samples[2][3][SCALE_BLOCK][SBLIMIT];
  1180. unsigned int j_scale[3][SBLIMIT];
  1181. double FAR j_samps[3][SCALE_BLOCK][SBLIMIT]; /* L+R for j-stereo if necess */
  1182. unsigned int bit_alloc[2][SBLIMIT];
  1183. unsigned int FAR sbband[2][3][SCALE_BLOCK][SBLIMIT];
  1184. frame_params *fr_ps;
  1185. {
  1186.    int i, j, k, n, sig;
  1187.    int stereo  = fr_ps->stereo;
  1188.    int sblimit = fr_ps->sblimit;
  1189.    int jsbound = fr_ps->jsbound;
  1190.    double d;
  1191. static char init = 0;
  1192.  
  1193.    if (!init) {
  1194.      init = 1;
  1195.      /* rearrange quantization coef to correspond to layer I table */
  1196.      a[1] = a[2]; b[1] = b[2];
  1197.      for (i=2;i<15;i++) { a[i] = a[i+2]; b[i] = b[i+2]; }
  1198.    }
  1199.    for (j=0;j<SCALE_BLOCK;j++) for (i=0;i<SBLIMIT;i++)
  1200.      for (k=0;k<((i<jsbound)?stereo:1);k++)
  1201.        if (bit_alloc[k][i]) {
  1202.          /* for joint stereo mode, have to construct a single subband stream
  1203.             for the js channels.  At present, we calculate a set of mono
  1204.             subband samples and pass them through the scaling system to
  1205.             generate an alternate normalised sample stream.
  1206.  
  1207.             Could normalise both streams (divide by their scfs), then average
  1208.             them.  In bad conditions, this could give rise to spurious
  1209.             cancellations.  Instead, we could just select the sb stream from
  1210.             the larger channel (higher scf), in which case _that_ channel
  1211.             would be 'properly' reconstructed, and the mate would just be a
  1212.             scaled version.  Spec recommends averaging the two (unnormalised)
  1213.             subband channels, then normalising this new signal without
  1214.             actually sending this scale factor... This means looking ahead.
  1215.          */
  1216.          if(stereo == 2 && i>=jsbound)
  1217.            /* use the joint data passed in */
  1218.            d = j_samps[0][j][i] / multiple[j_scale[0][i]];
  1219.          else
  1220.            d = sb_samples[k][0][j][i] / multiple[scalar[k][0][i]];
  1221.          /* scale and quantize floating point sample */
  1222.          n = bit_alloc[k][i];
  1223.          d = d * a[n-1] + b[n-1];
  1224.          /* extract MSB N-1 bits from the floating point sample */
  1225.          if (d >= 0) sig = 1;
  1226.          else { sig = 0; d += 1.0; }
  1227.          sbband[k][0][j][i] = (unsigned int) (d * (double) (1L<<n));
  1228.          /* tag the inverted sign bit to sbband at position N */
  1229.          if (sig) sbband[k][0][j][i] |= 1<<n;
  1230.        }
  1231. }
  1232.  
  1233. /***************************** Layer II  ********************************/
  1234.  
  1235. void II_subband_quantization(scalar, sb_samples, j_scale, j_samps,
  1236.                              bit_alloc, sbband, fr_ps)
  1237. unsigned int scalar[2][3][SBLIMIT];
  1238. double FAR sb_samples[2][3][SCALE_BLOCK][SBLIMIT];
  1239. unsigned int j_scale[3][SBLIMIT];
  1240. double FAR j_samps[3][SCALE_BLOCK][SBLIMIT];
  1241. unsigned int bit_alloc[2][SBLIMIT];
  1242. unsigned int FAR sbband[2][3][SCALE_BLOCK][SBLIMIT];
  1243. frame_params *fr_ps;
  1244. {
  1245.    int i, j, k, s, n, qnt, sig;
  1246.    int stereo  = fr_ps->stereo;
  1247.    int sblimit = fr_ps->sblimit;
  1248.    int jsbound = fr_ps->jsbound;
  1249.    unsigned int stps;
  1250.    double d;
  1251.    al_table *alloc = fr_ps->alloc;
  1252.  
  1253.    for (s=0;s<3;s++)
  1254.      for (j=0;j<SCALE_BLOCK;j++)
  1255.        for (i=0;i<sblimit;i++)
  1256.          for (k=0;k<((i<jsbound)?stereo:1);k++)
  1257.            if (bit_alloc[k][i]) {
  1258.              /* scale and quantize floating point sample */
  1259.              if(stereo == 2 && i>=jsbound)       /* use j-stereo samples */
  1260.                d = j_samps[s][j][i] / multiple[j_scale[s][i]];
  1261.              else
  1262.                d = sb_samples[k][s][j][i] / multiple[scalar[k][s][i]];
  1263.              if (mod(d) > 1.0)
  1264.                printf("Not scaled properly %d %d %d %d\n",k,s,j,i);
  1265.              qnt = (*alloc)[i][bit_alloc[k][i]].quant;
  1266.              d = d * a[qnt] + b[qnt];
  1267.              /* extract MSB N-1 bits from the floating point sample */
  1268.              if (d >= 0) sig = 1;
  1269.              else { sig = 0; d += 1.0; }
  1270.              n = 0;
  1271. #ifndef MS_DOS
  1272.              stps = (*alloc)[i][bit_alloc[k][i]].steps;
  1273.              while ((1L<<n) < stps) n++;
  1274. #else
  1275.              while  ( ( (unsigned long)(1L<<(long)n) <
  1276.                        ((unsigned long) ((*alloc)[i][bit_alloc[k][i]].steps)
  1277.                         & 0xffff
  1278.                         )
  1279.                        ) && ( n <16)
  1280.                      ) n++;
  1281. #endif
  1282.              n--;
  1283.              sbband[k][s][j][i] = (unsigned int) (d * (double) (1L<<n));
  1284.              /* tag the inverted sign bit to sbband at position N */
  1285.              /* The bit inversion is a must for grouping with 3,5,9 steps
  1286.                 so it is done for all subbands */
  1287.              if (sig) sbband[k][s][j][i] |= 1<<n;
  1288.            }
  1289.            for (s=0;s<3;s++)
  1290.              for (j=sblimit;j<SBLIMIT;j++)
  1291.                for (i=0;i<SCALE_BLOCK;i++) for (k=0;k<stereo;k++) sbband[k][s][i][j] = 0;
  1292. }
  1293.  
  1294. /************************************************************************
  1295. /*
  1296. /* I_encode_bit_alloc  (Layer I)
  1297. /* II_encode_bit_alloc (Layer II)
  1298. /*
  1299. /* PURPOSE:Writes bit allocation information onto bitstream
  1300. /*
  1301. /* Layer I uses 4 bits/subband for bit allocation information,
  1302. /* and Layer II uses 4,3,2, or 0 bits depending on the
  1303. /* quantization table used.
  1304. /*
  1305. /************************************************************************/
  1306.  
  1307. void I_encode_bit_alloc(bit_alloc, fr_ps, bs)
  1308. unsigned int bit_alloc[2][SBLIMIT];
  1309. frame_params *fr_ps;
  1310. Bit_stream_struc *bs;
  1311. {
  1312.    int i,k;
  1313.    int stereo  = fr_ps->stereo;
  1314.    int sblimit = fr_ps->sblimit;
  1315.    int jsbound = fr_ps->jsbound;
  1316.  
  1317.    for (i=0;i<SBLIMIT;i++)
  1318.      for (k=0;k<((i<jsbound)?stereo:1);k++) putbits(bs,bit_alloc[k][i],4);
  1319. }
  1320.  
  1321. /***************************** Layer II  ********************************/
  1322.  
  1323. void II_encode_bit_alloc(bit_alloc, fr_ps, bs)
  1324. unsigned int bit_alloc[2][SBLIMIT];
  1325. frame_params *fr_ps;
  1326. Bit_stream_struc *bs;
  1327. {
  1328.    int i,k;
  1329.    int stereo  = fr_ps->stereo;
  1330.    int sblimit = fr_ps->sblimit;
  1331.    int jsbound = fr_ps->jsbound;
  1332.    al_table *alloc = fr_ps->alloc;
  1333.  
  1334.    for (i=0;i<sblimit;i++)
  1335.      for (k=0;k<((i<jsbound)?stereo:1);k++)
  1336.        putbits(bs,bit_alloc[k][i],(*alloc)[i][0].bits);
  1337. }
  1338.  
  1339. /************************************************************************
  1340. /*
  1341. /* I_sample_encoding   (Layer I)
  1342. /* II_sample_encoding  (Layer II)
  1343. /*
  1344. /* PURPOSE:Put one frame of subband samples on to the bitstream
  1345. /*
  1346. /* SEMANTICS:  The number of bits allocated per sample is read from
  1347. /* the bit allocation information #bit_alloc#.  Layer 2
  1348. /* supports writing grouped samples for quantization steps
  1349. /* that are not a power of 2.
  1350. /*
  1351. /************************************************************************/
  1352.  
  1353. void I_sample_encoding(sbband, bit_alloc, fr_ps, bs)
  1354. unsigned int FAR sbband[2][3][SCALE_BLOCK][SBLIMIT];
  1355. unsigned int bit_alloc[2][SBLIMIT];
  1356. frame_params *fr_ps;
  1357. Bit_stream_struc *bs;
  1358. {
  1359.    int i,j,k;
  1360.    int stereo  = fr_ps->stereo;
  1361.    int sblimit = fr_ps->sblimit;
  1362.    int jsbound = fr_ps->jsbound;
  1363.  
  1364.    for(j=0;j<SCALE_BLOCK;j++) {
  1365.      for(i=0;i<SBLIMIT;i++)
  1366.        for(k=0;k<((i<jsbound)?stereo:1);k++)
  1367.          if(bit_alloc[k][i]) putbits(bs,sbband[k][0][j][i],bit_alloc[k][i]+1);
  1368.    }
  1369. }
  1370.  
  1371. /***************************** Layer II  ********************************/
  1372.  
  1373. void II_sample_encoding(sbband, bit_alloc, fr_ps, bs)
  1374. unsigned int FAR sbband[2][3][SCALE_BLOCK][SBLIMIT];
  1375. unsigned int bit_alloc[2][SBLIMIT];
  1376. frame_params *fr_ps;
  1377. Bit_stream_struc *bs;
  1378. {
  1379.    unsigned int temp;
  1380.    unsigned int i,j,k,s,x,y;
  1381.    int stereo  = fr_ps->stereo;
  1382.    int sblimit = fr_ps->sblimit;
  1383.    int jsbound = fr_ps->jsbound;
  1384.    al_table *alloc = fr_ps->alloc;
  1385.  
  1386.    for (s=0;s<3;s++)
  1387.      for (j=0;j<SCALE_BLOCK;j+=3)
  1388.        for (i=0;i<sblimit;i++)
  1389.          for (k=0;k<((i<jsbound)?stereo:1);k++)
  1390.            if (bit_alloc[k][i]) {
  1391.              if ((*alloc)[i][bit_alloc[k][i]].group == 3) {
  1392.                for (x=0;x<3;x++) putbits(bs,sbband[k][s][j+x][i],
  1393.                                          (*alloc)[i][bit_alloc[k][i]].bits);
  1394.              }
  1395.              else {
  1396.                y =(*alloc)[i][bit_alloc[k][i]].steps;
  1397.                temp = sbband[k][s][j][i] +
  1398.                       sbband[k][s][j+1][i] * y +
  1399.                       sbband[k][s][j+2][i] * y * y;
  1400.                putbits(bs,temp,(*alloc)[i][bit_alloc[k][i]].bits);
  1401.              }
  1402.            }
  1403. }
  1404.  
  1405. /************************************************************************
  1406. /*
  1407. /* encode_CRC
  1408. /*
  1409. /************************************************************************/
  1410.  
  1411. void encode_CRC(crc, bs)
  1412. unsigned int crc;
  1413. Bit_stream_struc *bs;
  1414. {
  1415.    putbits(bs, crc, 16);
  1416. }
  1417.